package com.resume.service.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.resume.dto.LoginResponse
import com.resume.dto.RegisterRequest
import com.resume.dto.UserInfo
import com.resume.entity.User
import com.resume.mapper.UserMapper
import com.resume.service.UserService
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service

@Service
class UserServiceImpl(
    private val userMapper: UserMapper,
    private val passwordEncoder: PasswordEncoder
) : UserService {

    override fun login(username: String, password: String): LoginResponse {
        val user = userMapper.selectOne(
            QueryWrapper<User>().eq("username", username)
        ) ?: throw RuntimeException("用户不存在")

        if (!passwordEncoder.matches(password, user.password)) {
            throw RuntimeException("密码错误")
        }

        if (user.status != 1) {
            throw RuntimeException("账户已被禁用")
        }

        // 这里应该生成JWT token，暂时返回模拟token
        val token = generateToken(user.id!!)
        
        return LoginResponse(
            token = token,
            user = UserInfo(
                id = user.id!!,
                username = user.username,
                email = user.email,
                nickname = user.nickname,
                avatar = user.avatar
            )
        )
    }

    override fun register(request: RegisterRequest): LoginResponse {
        // 检查用户名是否已存在
        val existingUser = userMapper.selectOne(
            QueryWrapper<User>().eq("username", request.username)
        )
        if (existingUser != null) {
            throw RuntimeException("用户名已存在")
        }

        // 检查邮箱是否已存在
        val existingEmail = userMapper.selectOne(
            QueryWrapper<User>().eq("email", request.email)
        )
        if (existingEmail != null) {
            throw RuntimeException("邮箱已存在")
        }

        // 创建新用户
        val user = User(
            username = request.username,
            email = request.email,
            password = passwordEncoder.encode(request.password),
            nickname = request.nickname,
            phone = request.phone
        )

        userMapper.insert(user)

        // 生成token并返回
        val token = generateToken(user.id!!)
        
        return LoginResponse(
            token = token,
            user = UserInfo(
                id = user.id!!,
                username = user.username,
                email = user.email,
                nickname = user.nickname,
                avatar = user.avatar
            )
        )
    }

    override fun logout(token: String) {
        // 这里应该将token加入黑名单或从Redis中删除
        // 暂时不做处理
    }

    private fun generateToken(userId: Long): String {
        // 这里应该使用JWT生成token
        // 暂时返回一个模拟的token
        return "mock-jwt-token-$userId-${System.currentTimeMillis()}"
    }
} 